package cn.wen.eeayjoke.presenter;

import com.google.gson.Gson;

import junit.framework.Test;

import cn.wen.core.log.LogUtils;
import cn.wen.core.net.RetrofitUtils;
import cn.wen.eeayjoke.config.URLConfig;
import cn.wen.eeayjoke.entity.bean.base.RequestBean;
import cn.wen.eeayjoke.entity.bean.base.ResponseBean;
import cn.wen.eeayjoke.net.ServerApi;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 请求网络业务的基类
 */

public class BasePresenter {
    protected static ServerApi mApi;
    private static final Gson gson = new Gson();

    public BasePresenter() {
        initApi();
    }

    private void initApi() {
        if (mApi == null) {
            String baseUrl = URLConfig.getInstance().baseUrl();
            mApi = RetrofitUtils.getInstance()
                    .initRetrofit(baseUrl)
                    .create(ServerApi.class);
            RetrofitUtils.getInstance()
                    .initRetrofit(baseUrl)
                    .create(Test.class);
        }
    }


    /**
     * 1. 转换
     * 统一处理一些动作
     */
    public static <T> void convert(Observable<ResponseBean<T>> observable, Observer<? super T> observer) {
        observable.map(new Function<ResponseBean<T>, T>() {
            @Override
            public T apply(ResponseBean<T> httpResult) throws Exception {
                // TODO 实际开发的时候统一处理一些东西
                if (httpResult == null || httpResult.head == null) {
                    throw new RuntimeException("请求数据异常");
                } else if (!"1".equals(httpResult.head.bcode)) {
                    throw new RuntimeException(httpResult.head.bmessage);
                }
                return httpResult.data;
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    public static <T> Observable<T> convert(Observable<ResponseBean<T>> observable) {
        return observable.flatMap(new Function<ResponseBean<T>, ObservableSource<T>>() {
            @Override
            public ObservableSource<T> apply(final ResponseBean<T> httpResult) throws Exception {
                if (httpResult == null || httpResult.head == null) {
                    return Observable.error(new RuntimeException("请求数据异常"));
                } else if (!"1".equals(httpResult.head.bcode)) {
                    return Observable.error(new RuntimeException(httpResult.head.bmessage));
                }
                return createObservable(httpResult.data);
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
    }

    public static <T> Observable<T> createObservable(final T data) {
        return Observable.create(new ObservableOnSubscribe<T>() {
            @Override
            public void subscribe(ObservableEmitter<T> e) throws Exception {
                e.onNext(data);
                e.onComplete();
            }
        });
    }

    /**
     * 2. 执行的方法
     */
    public static <T> void execute(Observable<ResponseBean<T>> observable, Observer<ResponseBean<T>> observer) {
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }

    /**
     * 请求数据是Json，Json转成RequestBody
     */
    public static RequestBody createRequestBody(Object obj) {
        RequestBean requestBean = new RequestBean<>(obj);
        String json = gson.toJson(requestBean);
        // 打印请求的Json
        LogUtils.json(json);
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
    }

    /**
     * 请求数据是Json，Json转成RequestBody
     */
    public static RequestBody createRequestBody() {
        return createRequestBody(null);
    }
}
